package com.scud.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.scud.common.error.ErrorConstants;
import com.scud.common.exception.ScudException;
import com.scud.common.regex.RegexPatterns;
import com.scud.model.system.dto.LoginDto;
import com.scud.model.system.pojo.User;
import com.scud.model.system.pojo.UserRole;
import com.scud.system.mapper.UserMapper;
import com.scud.system.mapper.UserRoleMapper;
import com.scud.system.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author vermouth
 */
@Service("manager_auth")
public class ManagerAuthServiceImpl implements AuthService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public User execute(LoginDto loginDto) {
        String phone = loginDto.getPhone();
        String password = loginDto.getPassword();
        //校验手机号
        if (StrUtil.isBlank(phone) || !phone.matches(RegexPatterns.PHONE_REGEX)){
            throw new ScudException(ErrorConstants.PHONE_ILL_LEGAL);
        }
        //根据手机号查询用户
        User user = userMapper.getUserByPhone(phone);
        //判断用户是否存在
        if (user==null){
            throw new ScudException(ErrorConstants.USER_NOT_EXISTS);
        }
        //判断是否为后台系统人员
        List<UserRole> list= userRoleMapper.selectByUserId(user.getId());
        if (list==null){
            throw new ScudException(ErrorConstants.USER_ILL_LEGAL);
        }
        //判断密码是否正确
        if (StrUtil.isBlank(password) || !passwordEncoder.matches(password,user.getPassword())){
            throw new ScudException(ErrorConstants.PASSWORD_ERROR);
        }

        return user;
    }
}
